package com.lyz.mail;

import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import org.apache.log4j.Logger;

@SuppressWarnings("rawtypes")
public class SendMail {

	private static Logger logger = Logger.getLogger(SendMail.class);
	protected String mailTo = null;
	protected String mailFrom = null;
	protected String smtpHost = null;
	protected boolean debug = false;

	protected String messageBasePath = null;
	protected String subject;
	protected String msgContent;

	protected Vector attachedFileList;
	protected String mailAccount = null;
	protected String mailPass = null;
	protected String messageContentMimeType = "text/html; charset=gb2312";

	protected String mailbccTo = null;
	protected String mailccTo = null;

	protected String __time;
	/**
	 * SendMailService 构造子注解。
	 */
	public SendMail() {
		__time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
	}

	private void fillMail(Session session, MimeMessage msg) throws IOException,
			MessagingException {

		String fileName = null;
		Multipart mPart = new MimeMultipart();
		if (mailFrom != null) {
			msg.setFrom(new InternetAddress(mailFrom));
			//System.out.println("发送人Mail地址：" + mailFrom);
		} else {
			//System.out.println("没有指定发送人邮件地址！");
			return;
		}
		if (mailTo != null) {
			InternetAddress[] address = InternetAddress.parse(mailTo);
			msg.setRecipients(Message.RecipientType.TO, address);
			//System.out.println("收件人Mail地址：" + mailTo);
		} else {
			//System.out.println("没有指定收件人邮件地址！");
			return;
		}

		if (mailccTo != null) {
			InternetAddress[] ccaddress = InternetAddress.parse(mailccTo);
			//System.out.println("CCMail地址：" + mailccTo);
			msg.setRecipients(Message.RecipientType.CC, ccaddress);
		}
		if (mailbccTo != null) {
			InternetAddress[] bccaddress = InternetAddress.parse(mailbccTo);
			//System.out.println("BCCMail地址：" + mailbccTo);
			msg.setRecipients(Message.RecipientType.BCC, bccaddress);
		}
		msg.setSubject(subject);
		InternetAddress[] replyAddress = { new InternetAddress(mailFrom) };
		msg.setReplyTo(replyAddress);
		// create and fill the first message part
		MimeBodyPart mBodyContent = new MimeBodyPart();
		if (msgContent != null)
			mBodyContent.setContent(msgContent, messageContentMimeType);
		else
			mBodyContent.setContent("", messageContentMimeType);
		mPart.addBodyPart(mBodyContent);
		// attach the file to the message
		if (attachedFileList != null) {
			for (Enumeration fileList = attachedFileList.elements(); fileList
					.hasMoreElements();) {
				fileName = (String) fileList.nextElement();
				MimeBodyPart mBodyPart = new MimeBodyPart();

				// attach the file to the message
				FileDataSource fds = new FileDataSource(messageBasePath
						+ fileName);
				//System.out.println("Mail发送的附件为：" + messageBasePath + fileName);
				mBodyPart.setDataHandler(new DataHandler(fds));
				mBodyPart.setFileName(fileName);
				mPart.addBodyPart(mBodyPart);
			}
		}
		msg.setContent(mPart);
		msg.setSentDate(new Date());
	}

	/**
	 * 此处插入方法说明。
	 */
	public void init() {

	}

	/**
	 * 发送e_mail，返回类型为int 当返回值为0时，说明邮件发送成功 当返回值为3时，说明邮件发送失败
	 */
	public int sendMail() throws IOException, MessagingException {
//		int loopCount = 0;
		Properties props = System.getProperties();
		props.put("mail.smtp.host", smtpHost);
		props.put("mail.smtp.auth", "true");

		MailAuthenticator auth = new MailAuthenticator();

		Session session = Session.getInstance(props, auth);
		session.setDebug(debug);
		MimeMessage msg = new MimeMessage(session);
		Transport trans = null;
		try {

			fillMail(session, msg);
			// send the message
			trans = session.getTransport("smtp");
			try {
				trans.connect(smtpHost, MailAuthenticator.HUAWEI_MAIL_USER,
						MailAuthenticator.HUAWEI_MAIL_PASSWORD);// ,
																// HUAWEI_MAIL_PASSWORD);
			} catch (AuthenticationFailedException e) {
				logger.error(e);
				//System.out.println("连接邮件服务器错误：");
				return 3;
			} catch (MessagingException e) {
				//System.out.println("连接邮件服务器错误：");
				logger.error(e);
				return 3;
			}

			Transport.send(msg);
			trans.close();

		} catch (MessagingException mex) {
			//System.out.println("发送邮件失败：");
			mex.printStackTrace();
			Exception ex = null;
			if ((ex = mex.getNextException()) != null) {
				//System.out.println(ex.toString());
				logger.error(ex);
			}
			return 3;
		} finally {
			try {
				if (trans != null && trans.isConnected())
					trans.close();
			} catch (Exception e) {
				logger.error(e);
			}
		}
		//System.out.println("发送邮件成功！");
		return 0;
	}

	public void setAttachedFileList(Vector filelist) {
		this.attachedFileList = filelist;
	}

	public void setDebug(boolean debugFlag) {
		this.debug = debugFlag;
	}

	public void setMailAccount(String strAccount) {
		this.mailAccount = strAccount;
	}

	public void setMailbccTo(String bccto) {
		this.mailbccTo = bccto;
	}

	public void setMailccTo(String ccto) {
		this.mailccTo = ccto;
	}

	public void setMailFrom(String from) {
		this.mailFrom = from;
	}

	public void setMailPass(String strMailPass) {
		this.mailPass = strMailPass;
	}

	public void setMailTo(String to) {
		this.mailTo = to;
	}

	public void setMessageBasePath(String basePath) {
		this.messageBasePath = basePath;
	}

	public void setMessageContentMimeType(String mimeType) {
		this.messageContentMimeType = mimeType;
	}

	public void setMsgContent(String content) {
		this.msgContent = content;
	}

	public void setSMTPHost(String host) {
		this.smtpHost = host;
	}

	public void setSubject(String sub) {
		this.subject = sub;
	}
	
	public static void sendMail(String subject, String content,String mailHost, String mailFrom, String mailTo) {
		logger.info("one mail is sending...");
		SendMail sm = new SendMail();
		sm.setSMTPHost(mailHost);
		sm.setMailFrom(mailFrom);
		sm.setMailTo(mailTo);
		sm.setSubject(subject);
		sm.setMsgContent(content);
		
		try {
			sm.sendMail();
		} catch (Exception e) {
			logger.error(e);
		}
		sm = null;
	}
	
	
}